package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.article.ArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.AggBehaviorDTO;
import com.heima.utils.common.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
@Slf4j
public class HotArticleServiceImpl implements HotArticleService {
    @Autowired
    ApArticleMapper apArticleMapper;

    @Override
    public void computeHotArticle() {
        //1. 查询近5天的文章数据
        List<ApArticle> list = getArcticleList();
        if (CollectionUtils.isEmpty(list)) {
            log.info("太冷清了，近5天没人在我们的app上发表文章 ~~~");
            return;
        }
        //2.计算篾片文章的分值
        List<HotArticleVo> hotArticleVoList = getHotArticleVoList(list);
        //3.按照频道将每个频道最热门的的30条文章缓存
        cacheRedisByTag(hotArticleVoList);

    }


    @Override
    public void updateApArticle(AggBehaviorDTO aggBehavior) {
        //1.根据聚合结果中的文章ID 查询文章数据
        ApArticle article = apArticleMapper.selectById(aggBehavior.getArticleId());
        //2.根据聚合结果中各行为的值 修改文章中行为总量的值
        article.setViews((int) (article.getViews() + aggBehavior.getView()));
        article.setLikes((int) (article.getLikes() + aggBehavior.getLike()));
        article.setComment((int) (article.getComment() + aggBehavior.getComment()));
        article.setCollection((int) (article.getCollection() + aggBehavior.getCollect()));
        //3.修改文章
        apArticleMapper.updateById(article);
        //4.重新计算文章热度得分
        Integer score = computeScore(article);
        //5.如果文章是今天发布的 整体热度*3
        String publishTime = DateUtils.dateToString(article.getPublishTime());
        String nowTime = DateUtils.dateToString(new Date());
        if (publishTime.equals(nowTime)) {
            score = score * 3;
        }
        //6.查询对应的频道热点文章，替换分值较低的热点文章
        updateApArticleCache(article, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + article.getChannelId());
        //7.查询对应的推荐频道热点文章，替换分支较低的热点文章
        updateApArticleCache(article, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);

    }


    /**
     * 更新缓存热点文章
     *
     * @param article
     * @param score    最新文章热度得分
     * @param cacheKey 缓存key
     */
    private void updateApArticleCache(ApArticle article, Integer score, String cacheKey) {
        //1.根据缓存key 查询对应的热点文章列表
        String hotArticleJson = redisTemplate.opsForValue().get(cacheKey);
        if (StringUtils.isEmpty(hotArticleJson)) {
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR, "所属频道 热点文章不存在");
        }
        List<HotArticleVo> hotArticleVoList = JSON.parseArray(hotArticleJson, HotArticleVo.class);
        //2.判断当前文章是否已经存在热点文章列表
        boolean isHas = false;
        for (HotArticleVo hotArticleVo : hotArticleVoList) {
            //2.1 如果已经存在，修改热点分值
            if (hotArticleVo.getId().equals(article.getId())) {
                hotArticleVo.setScore(score);
                isHas = true;
                break;
            }
        }
        //2.2如果不存在 将当前文章加入到热点文章列表
        if (!isHas) {
            HotArticleVo articleVo = new HotArticleVo();
            BeanUtils.copyProperties(article, articleVo);
            articleVo.setScore(score);
            hotArticleVoList.add(articleVo);
        }
        //3.将热点文章按照热度 降序排序 截取前30条文章
        hotArticleVoList = hotArticleVoList.stream()
                .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                .limit(30)
                .collect(Collectors.toList());
        //4.保存redis缓存中
        redisTemplate.opsForValue().set(cacheKey,JSON.toJSONString(hotArticleVoList));
    }

    @Autowired
    AdminFeign adminFeign;

    /**
     * 将热点文章缓存到redis中
     *
     * @param hotArticleVoList
     */
    private void cacheRedisByTag(List<HotArticleVo> hotArticleVoList) {
        //1.使用feign查询频道列表
        ResponseResult<List<AdChannel>> result = adminFeign.selectChannels();
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程调用频道列表失败");
        }
        //2.遍历频道列表
        List<AdChannel> channelList = result.getData();
        for (AdChannel adChannel : channelList) {
            //找出每个频道对应的文章 进行缓存
            List<HotArticleVo> articleVoListByTag = hotArticleVoList.stream()
                    .filter(hotArticleVo -> hotArticleVo.getChannelId().equals(adChannel.getId()))
                    .collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(articleVoListByTag)) {
                sortAndCache(articleVoListByTag, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + adChannel.getId());
            }
        }
        //3.推荐频道
        //直接根据所有文章数据 进行缓存
        sortAndCache(hotArticleVoList, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);
    }

    /**
     * 将文章缓存到redis
     *
     * @param articleVoList
     * @param cacheKey
     */
    @Autowired
    StringRedisTemplate redisTemplate;

    private void sortAndCache(List<HotArticleVo> articleVoList, String cacheKey) {
        //将带有分值的文章列表 按照文章热度 将序排序 截取前30条文章
        List<HotArticleVo> hotArticleVos = articleVoList.stream()
                //按照文章热度 将序排序
                .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                //截取前30条文章
                .limit(30)
                .collect(Collectors.toList());
        //将文章缓存到redis中
        redisTemplate.opsForValue().set(cacheKey, JSON.toJSONString(hotArticleVos));
    }

    /**
     * 计算每天文章的热度值
     *
     * @param list
     * @return
     */
    private List<HotArticleVo> getHotArticleVoList(List<ApArticle> list) {
        return list.stream()
                .map(article -> {
                    HotArticleVo articleVo = new HotArticleVo();
                    BeanUtils.copyProperties(article, articleVo);
                    Integer score = computeScore(article);
                    articleVo.setScore(score);
                    return articleVo;
                }).collect(Collectors.toList());

    }

    /**
     * 计算每篇文章的热度得分
     *
     * @param article
     * @return
     */
    private Integer computeScore(ApArticle article) {
        Integer score = 0;
        //阅读
        if (article.getViews() != null) {
            score += article.getViews() * ArticleConstants.HOT_ARTICLE_VIEW_WEIGHT;
        }
        //点赞
        if (article.getLikes() != null) {
            score += article.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        //评论
        if (article.getComment() != null) {
            score += article.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        //收藏
        if (article.getCollection() != null) {
            score += article.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        return score;
    }

    /**
     * 查询近5天文章搞定
     *
     * @return
     */
    private List<ApArticle> getArcticleList() {
        //1. 计算5天前的时间
        String dateParam = LocalDateTime.now()
                .minusDays(5)
                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        //2.调用aeticleMapper按照时间查询
        List<ApArticle> articleList = apArticleMapper.selectArticleByDate(dateParam);
        return articleList;
    }
}
